import React, { useEffect, useState, useRef } from 'react';
import * as echarts from 'echarts';
import type { EChartsOption } from 'echarts';

interface BarData {
  timestamp: string;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
  amount: number;
}

interface Statistics {
  count: number;
  time_range: {
    start: string;
    end: string;
  };
  price_range: {
    open: number;
    close: number;
    high: number;
    low: number;
    change: number;
    change_percent: number;
  };
  volume: {
    total: number;
    average: number;
  };
}

interface DemoData {
  symbol: string;
  name: string;
  frequency: string;
  frequency_display: string;
  bars: BarData[];
  statistics: Statistics;
}

interface ApiResponse {
  success: boolean;
  data: DemoData | null;
  message?: string;
  timestamp: string;
}

const MarketDemo: React.FC = () => {
  const [data, setData] = useState<DemoData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [days, setDays] = useState(7);
  const [frequency, setFrequency] = useState('1d');
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await fetch(
        `/api/v1/market/demo/index-bars?days=${days}&limit=100&frequency=${frequency}`
      );
      
      if (!response.ok) {
        throw new Error(`HTTP错误: ${response.status}`);
      }
      
      const result: ApiResponse = await response.json();
      
      if (result.success && result.data) {
        setData(result.data);
      } else {
        setError(result.message || '获取数据失败');
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : '网络请求失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始加载
  useEffect(() => {
    fetchData();
  }, []);

  // 更新图表
  useEffect(() => {
    if (!data || !chartRef.current) return;

    // 初始化或获取图表实例
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }

    const chart = chartInstance.current;

    // 准备K线数据
    const dates = data.bars.map(bar => bar.timestamp.substring(0, 16));
    const klineData = data.bars.map(bar => [bar.open, bar.close, bar.low, bar.high]);
    const volumes = data.bars.map(bar => bar.volume);

    // 配置图表
    const option: EChartsOption = {
      title: {
        text: `${data.name} (${data.symbol})`,
        subtext: data.frequency_display,
        left: 'center',
        textStyle: {
          fontSize: 18,
          fontWeight: 'bold'
        }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        },
        formatter: function (params: any) {
          const p = params[0];
          if (!p) return '';
          const idx = p.dataIndex;
          const bar = data.bars[idx];
          return `
            <div style="padding: 8px;">
              <div style="font-weight: bold; margin-bottom: 4px;">${dates[idx]}</div>
              <div>开盘: ${bar.open.toFixed(2)}</div>
              <div>收盘: ${bar.close.toFixed(2)}</div>
              <div>最高: ${bar.high.toFixed(2)}</div>
              <div>最低: ${bar.low.toFixed(2)}</div>
              <div>成交量: ${(bar.volume / 10000).toFixed(2)}万手</div>
            </div>
          `;
        }
      },
      legend: {
        data: ['K线', '成交量'],
        top: 30
      },
      grid: [
        {
          left: '10%',
          right: '10%',
          top: '15%',
          height: '50%'
        },
        {
          left: '10%',
          right: '10%',
          top: '70%',
          height: '15%'
        }
      ],
      xAxis: [
        {
          type: 'category',
          data: dates,
          boundaryGap: false,
          axisLine: { onZero: false },
          splitLine: { show: false },
          min: 'dataMin',
          max: 'dataMax',
          axisLabel: {
            formatter: function (value: string) {
              return value.substring(5); // 只显示月-日 时:分
            }
          }
        },
        {
          type: 'category',
          gridIndex: 1,
          data: dates,
          boundaryGap: false,
          axisLine: { onZero: false },
          axisTick: { show: false },
          splitLine: { show: false },
          axisLabel: { show: false },
          min: 'dataMin',
          max: 'dataMax'
        }
      ],
      yAxis: [
        {
          scale: true,
          splitArea: {
            show: true
          }
        },
        {
          scale: true,
          gridIndex: 1,
          splitNumber: 2,
          axisLabel: { show: false },
          axisLine: { show: false },
          axisTick: { show: false },
          splitLine: { show: false }
        }
      ],
      dataZoom: [
        {
          type: 'inside',
          xAxisIndex: [0, 1],
          start: 0,
          end: 100
        },
        {
          show: true,
          xAxisIndex: [0, 1],
          type: 'slider',
          top: '90%',
          start: 0,
          end: 100
        }
      ],
      series: [
        {
          name: 'K线',
          type: 'candlestick',
          data: klineData,
          itemStyle: {
            color: '#ef5350',
            color0: '#26a69a',
            borderColor: '#ef5350',
            borderColor0: '#26a69a'
          }
        },
        {
          name: '成交量',
          type: 'bar',
          xAxisIndex: 1,
          yAxisIndex: 1,
          data: volumes,
          itemStyle: {
            color: function (params: any) {
              const idx = params.dataIndex;
              const bar = data.bars[idx];
              return bar.close >= bar.open ? '#ef5350' : '#26a69a';
            }
          }
        }
      ]
    };

    chart.setOption(option);

    // 响应式调整
    const handleResize = () => {
      chart.resize();
    };
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [data]);

  // 清理图表
  useEffect(() => {
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, []);

  return (
    <div style={{ padding: '24px', backgroundColor: '#f5f5f5', minHeight: '100vh' }}>
      {/* 页面标题 */}
      <div style={{
        backgroundColor: 'white',
        padding: '24px',
        borderRadius: '8px',
        marginBottom: '24px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <h1 style={{ margin: '0 0 8px 0', fontSize: '28px', color: '#333' }}>
          📊 市场数据演示
        </h1>
        <p style={{ margin: 0, color: '#666', fontSize: '14px' }}>
          实时获取上证指数K线数据，验证Market Data Service可用性
        </p>
      </div>

      {/* 控制面板 */}
      <div style={{
        backgroundColor: 'white',
        padding: '20px',
        borderRadius: '8px',
        marginBottom: '24px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <h3 style={{ margin: '0 0 16px 0', fontSize: '16px' }}>查询参数</h3>
        <div style={{ display: 'flex', gap: '16px', alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <label style={{ fontSize: '14px', color: '#666' }}>时间范围:</label>
            <select
              value={days}
              onChange={(e) => setDays(Number(e.target.value))}
              style={{
                padding: '6px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                fontSize: '14px'
              }}
            >
              <option value={1}>最近1天</option>
              <option value={7}>最近7天</option>
              <option value={30}>最近30天</option>
            </select>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
            <label style={{ fontSize: '14px', color: '#666' }}>K线周期:</label>
            <select
              value={frequency}
              onChange={(e) => setFrequency(e.target.value)}
              style={{
                padding: '6px 12px',
                border: '1px solid #d9d9d9',
                borderRadius: '4px',
                fontSize: '14px'
              }}
            >
              <option value="1m">1分钟</option>
              <option value="5m">5分钟</option>
              <option value="15m">15分钟</option>
              <option value="30m">30分钟</option>
              <option value="1h">1小时</option>
              <option value="1d">日线</option>
            </select>
          </div>

          <button
            onClick={fetchData}
            disabled={loading}
            style={{
              padding: '6px 24px',
              backgroundColor: loading ? '#d9d9d9' : '#1890ff',
              color: 'white',
              border: 'none',
              borderRadius: '4px',
              cursor: loading ? 'not-allowed' : 'pointer',
              fontSize: '14px',
              fontWeight: '500'
            }}
          >
            {loading ? '加载中...' : '刷新数据'}
          </button>
        </div>
      </div>

      {/* 统计信息面板 */}
      {data && data.statistics && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))',
          gap: '16px',
          marginBottom: '24px'
        }}>
          <div style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '4px' }}>数据条数</div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#333' }}>
              {data.statistics.count}
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '4px' }}>开盘价</div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#333' }}>
              {data.statistics.price_range.open.toFixed(2)}
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '4px' }}>收盘价</div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#333' }}>
              {data.statistics.price_range.close.toFixed(2)}
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '4px' }}>涨跌幅</div>
            <div style={{
              fontSize: '24px',
              fontWeight: 'bold',
              color: data.statistics.price_range.change >= 0 ? '#52c41a' : '#ff4d4f'
            }}>
              {data.statistics.price_range.change >= 0 ? '+' : ''}
              {data.statistics.price_range.change_percent.toFixed(2)}%
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '4px' }}>区间最高</div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#333' }}>
              {data.statistics.price_range.high.toFixed(2)}
            </div>
          </div>

          <div style={{
            backgroundColor: 'white',
            padding: '20px',
            borderRadius: '8px',
            boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
          }}>
            <div style={{ fontSize: '12px', color: '#999', marginBottom: '4px' }}>区间最低</div>
            <div style={{ fontSize: '24px', fontWeight: 'bold', color: '#333' }}>
              {data.statistics.price_range.low.toFixed(2)}
            </div>
          </div>
        </div>
      )}

      {/* K线图表 */}
      <div style={{
        backgroundColor: 'white',
        padding: '24px',
        borderRadius: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        marginBottom: '24px'
      }}>
        {loading && (
          <div style={{
            height: '500px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#999'
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '48px', marginBottom: '16px' }}>⏳</div>
              <div>正在加载数据...</div>
            </div>
          </div>
        )}

        {error && (
          <div style={{
            height: '500px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#ff4d4f'
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '48px', marginBottom: '16px' }}>❌</div>
              <div style={{ fontSize: '16px', fontWeight: '500', marginBottom: '8px' }}>
                数据加载失败
              </div>
              <div style={{ fontSize: '14px', color: '#999' }}>
                {error}
              </div>
              <button
                onClick={fetchData}
                style={{
                  marginTop: '16px',
                  padding: '8px 24px',
                  backgroundColor: '#1890ff',
                  color: 'white',
                  border: 'none',
                  borderRadius: '4px',
                  cursor: 'pointer',
                  fontSize: '14px'
                }}
              >
                重试
              </button>
            </div>
          </div>
        )}

        {!loading && !error && data && (
          <div ref={chartRef} style={{ width: '100%', height: '500px' }} />
        )}

        {!loading && !error && !data && (
          <div style={{
            height: '500px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: '#999'
          }}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: '48px', marginBottom: '16px' }}>📊</div>
              <div>点击"刷新数据"按钮获取K线数据</div>
            </div>
          </div>
        )}
      </div>

      {/* API信息 */}
      {data && (
        <div style={{
          backgroundColor: 'white',
          padding: '20px',
          borderRadius: '8px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <h3 style={{ margin: '0 0 12px 0', fontSize: '16px' }}>📡 API调用信息</h3>
          <div style={{ fontSize: '13px', color: '#666', lineHeight: '1.8' }}>
            <div><strong>端点:</strong> GET /api/v1/market/demo/index-bars</div>
            <div><strong>参数:</strong> days={days}, frequency={frequency}, limit=100</div>
            <div><strong>标的:</strong> {data.symbol} ({data.name})</div>
            <div><strong>时间范围:</strong> {data.statistics.time_range.start.substring(0, 16)} ~ {data.statistics.time_range.end.substring(0, 16)}</div>
            <div><strong>数据条数:</strong> {data.statistics.count}</div>
          </div>
        </div>
      )}
    </div>
  );
};

export default MarketDemo;

